package com.zhiche.lisa.lspm.service.lsp.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.zhiche.lisa.core.enums.*;
import com.zhiche.lisa.core.enums.exception.LspEnum;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.supports.RestfulResponse;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.RegexUtil;
import com.zhiche.lisa.core.utils.WeiXinUtil;
import com.zhiche.lisa.lspm.dao.mapper.lsp.LspInfoMapper;
import com.zhiche.lisa.lspm.dao.model.BusinessRelation;
import com.zhiche.lisa.lspm.dao.model.carrier.CarrierInfo;
import com.zhiche.lisa.lspm.dao.model.driver.Driver;
import com.zhiche.lisa.lspm.dao.model.driver.DriverCheckin;
import com.zhiche.lisa.lspm.dao.model.fleet.Fleet;
import com.zhiche.lisa.lspm.dao.model.fleet.FleetAdmin;
import com.zhiche.lisa.lspm.dao.model.lsp.*;
import com.zhiche.lisa.lspm.dao.model.lsp.bo.*;
import com.zhiche.lisa.lspm.dao.model.sys.User;
import com.zhiche.lisa.lspm.dao.model.sys.UserRole;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerInfo;
import com.zhiche.lisa.lspm.dto.ArFundDTO;
import com.zhiche.lisa.lspm.dto.DriverDTO;
import com.zhiche.lisa.lspm.dto.LspInfoDTO;
import com.zhiche.lisa.lspm.dto.VehicleDTO;
import com.zhiche.lisa.lspm.service.BusinessRelation.BusinessRelationService;
import com.zhiche.lisa.lspm.service.carrier.ICarrierAuditLogService;
import com.zhiche.lisa.lspm.service.carrier.ICarrierInfoService;
import com.zhiche.lisa.lspm.service.driver.IDriverAuditLogService;
import com.zhiche.lisa.lspm.service.driver.IDriverCheckinService;
import com.zhiche.lisa.lspm.service.driver.IDriverService;
import com.zhiche.lisa.lspm.service.fleet.FleetAdminService;
import com.zhiche.lisa.lspm.service.fleet.IFleetService;
import com.zhiche.lisa.lspm.service.license.LicenseServier;
import com.zhiche.lisa.lspm.service.lsp.*;
import com.zhiche.lisa.lspm.service.sys.IUserRoleService;
import com.zhiche.lisa.lspm.service.sys.IUserService;
import com.zhiche.lisa.lspm.service.trailer.ITrailerAuditLogService;
import com.zhiche.lisa.lspm.service.trailer.TrailerInfoService;
import com.zhiche.lisa.lspm.service.utils.DevopUtil;
import com.zhiche.lisa.lspm.service.utils.IntegrationUtil;
import com.zhiche.lisa.lspm.service.utils.MdmUtil;
import com.zhiche.lisa.lspm.service.utils.UaaUtil;
import com.zhiche.lisa.lspm.vo.attach.LicenseDetailVO;
import com.zhiche.lisa.lspm.vo.attach.LicenseVO;
import com.zhiche.lisa.lspm.vo.common.*;
import com.zhiche.lisa.lspm.vo.lsp.*;
import com.zhiche.lisa.lspm.vo.vehicle.WeChatVehicle;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.jms.Destination;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 承运商 service impl
 *
 * @author lbl
 * @since 2018-05-23
 */
@Service
public class LspInfoServiceImpl extends ServiceImpl<LspInfoMapper, LspInfo> implements LspInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(LspInfoServiceImpl.class);

    @Value("${permission.createsharingrule}")
    private String CREATE_TENANT_SHARING_RULE_URI;
    @Value("${lisa.tms.lspWaybillUrl}")
    private String lspWaybillUrl;

    @Autowired
    private IntegrationUtil integrationUtil;

    @Autowired
    private LspAuditLogService lspAuditLogService;

    @Autowired
    private LspLicenseService lspLicenseService;

    @Autowired
    private LspLicenseAttachService licenseAttachService;

    @Autowired
    private LspBankAccountService lspBankAccountService;

    @Autowired
    private LspCardService lspCardService;

    @Autowired
    private ICarrierInfoService carrierInfoService;

    @Autowired
    private ICarrierAuditLogService carrierAuditLogService;

    @Autowired
    private TrailerInfoService trailerInfoService;

    @Autowired
    private ITrailerAuditLogService trailerAuditLogService;

    @Autowired
    private IDriverService driverService;

    @Autowired
    private IDriverAuditLogService driverAuditLogService;

    @Autowired
    private BusinessRelationService businessRelationService;

    @Autowired
    private MdmUtil mdmUtil;

    @Autowired
    private UaaUtil uaaUtil;

    @Autowired
    private DevopUtil devopUtil;

    @Autowired
    private LspCreateLogService lspCreateLogService;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IUserService userService;

    @Autowired
    private JmsTemplate jmsTemplate;

    @Autowired
    private LicenseServier licenseServier;

    @Autowired
    private FleetAdminService fleetAdminService;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IFleetService fleetService;
    @Autowired
    private LspInfoService lspInfoService;
    @Autowired
    private IDriverCheckinService driverCheckinService;


    @Value("${mqName.lsp}")
    private String mqNameLsp;

    @Value("${lisa.lspm.registerLspUrl}")
    private String registerLspUrl;

    @Value("${uaa.getTenantDredgeUrl}")
    private String getTenantDredgeUrl;

    @Value("${uaa.socketTimeout}")
    private Integer socketTimeout;

    @Value("${uaa.tenantIsRegisteredUrl}")
    private String tenantIsRegisteredUrl;

    @Value("${uaa.url}")
    private String uaaUrl;


    @Value("${uaa.openUpTenantUrl}")
    private String openUpTenantUrl;

    @Override
    public Page<LspBasicVO> lspInfoLine(Page<LspInfoLineVO> page, String authorization) {
        Page<LspBasicVO> pageVo = new Page<>();
        List<LspBasicVO> list = baseMapper.lspInfoLine(page, buildConditionInfo(page.getCondition()));
        BeanUtils.copyProperties(page, pageVo);
        list.forEach(LspInfoLineVO -> {
            if (!Strings.isNullOrEmpty(LspInfoLineVO.getCreator())) {
                AccountVO accountVO = uaaUtil.getAccountById(LspInfoLineVO.getCreator(), authorization);
                if (Objects.nonNull(accountVO)) {
                    LspInfoLineVO.setCreator(accountVO.getIdentifier());
                }
            }
            if (!StringUtils.isEmpty(LspInfoLineVO.getServiceType())) {
                List<TransportationTypeVO> allServiceType = mdmUtil.getAllTransportType();
                String serviceTypeName = LspInfoLineVO.getServiceType();
                for (TransportationTypeVO transportationTypeVO :
                        allServiceType) {
                    serviceTypeName = serviceTypeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getValue());
                }
                LspInfoLineVO.setServiceTypeName(serviceTypeName);
            }
        });
        pageVo.setRecords(list);
        return pageVo;
    }


    public Page<LspBlackLineVO> lspBlackLine(Page<LspBlackBO> page) {
        Page<LspBlackLineVO> pageVo = new Page<>();
        EntityWrapper<LspBlackBO> ew = new EntityWrapper<>();
        if (!Objects.isNull(page.getCondition())) {
            Object name = page.getCondition().get("name");
            Object serviceType = page.getCondition().get("serviceType");
            Object status = page.getCondition().get("status");
            Object authStatus = page.getCondition().get("authStatus");

            if (!(Objects.isNull(name) || "".equals(name))) ew.like("name", name.toString());
            if (!(Objects.isNull(serviceType) || "".equals(serviceType)))
                ew.like("service_type", serviceType.toString());
            if (!(Objects.isNull(status) || "".equals(status))) ew.eq("status", status.toString());
            if (!(Objects.isNull(authStatus) || "".equals(authStatus))) ew.eq("auth_status", authStatus.toString());
        }
        List<LspBlackLineVO> list = baseMapper.lspBlackLine(page, ew);
        BeanUtils.copyProperties(page, pageVo);
        list.forEach(LspBlackLineVO -> LspBlackLineVO.setServiceTypeName(mdmUtil.getServiceTypeByCodes(LspBlackLineVO
                .getServiceType())));
        pageVo.setRecords(list);
        return pageVo;
    }

    @Override
    public void lspInBlack(Integer ispId, String inlistReason) {
        if ((Objects.isNull(ispId))) throw new BaseException("未绑定拉黑的承运商");
        EntityWrapper<LspBlackBO> ew = new EntityWrapper<>();
        ew.eq("lli.id", ispId);
        List<LspBlackLineVO> list = baseMapper.lspBlackLine(new Page<>(), ew);
        if (!CollectionUtils.isEmpty(list)) throw new BaseException("该承运商已被拉黑,不能再次被拉黑");
        baseMapper.lspInBlack(ispId, new Date(), inlistReason);
    }

    @Override
    public void lspCleanBlack(Integer ispId, String outlistReason) {
        if ((Objects.isNull(ispId))) throw new BaseException("未绑定拉黑的承运商");
        EntityWrapper<LspBlackBO> ew = new EntityWrapper<>();
        ew.eq("lli.id", ispId);
        List<LspBlackLineVO> list = baseMapper.lspBlackLine(new Page<>(), ew);
        if (CollectionUtils.isEmpty(list)) throw new BaseException("该承运商未被拉黑");
        baseMapper.lspOutBlack(ispId, new Date(), outlistReason);
    }

    @Override
    public Page<LspAuthLineVO> lspAuthLine(Page<LspAuthLineBO> page) {
        Page<LspAuthLineVO> pageVo = new Page<>();
        List<LspAuthLineVO> list = baseMapper.lspAuthLine(page, buildConditionLspAuthLineBO(page.getCondition()));
        BeanUtils.copyProperties(page, pageVo);
        List<TransportationTypeVO> transportationTypeVOS = mdmUtil.getAllTransportType();
        list.forEach(lspAuthLineVO -> {
            if (!StringUtils.isEmpty(lspAuthLineVO.getServiceType())) {
                String typeName = lspAuthLineVO.getServiceType();
                for (TransportationTypeVO transportationTypeVO :
                        transportationTypeVOS) {
                    typeName = typeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getValue());
                }
                lspAuthLineVO.setServiceTypeName(typeName);
            }
        });
        pageVo.setRecords(list);
        return pageVo;
    }

    @Override
    public Page<AfterAuthLspLineVO> afterAuthLspLine(Page<AfterAuthLspLineBO> page) {
        Page<AfterAuthLspLineVO> pageVo = new Page<>();
        List<AfterAuthLspLineVO> list = baseMapper.afterAuthLspLine(page, buildCondition(page.getCondition()));
        //拷贝page对象
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(list);
        return pageVo;
    }


    @Transactional
    @Override
    public void addLspInfo(ModifyLspInfoBO modifyLspInfoBO, String authorization) {
        try {
            LspInfo lspInfo = new LspInfo();
            // 校验数据
            checkModifyData(modifyLspInfoBO, "insert");

            if (modifyLspInfoBO.getBusinessSite() != null
                    && modifyLspInfoBO.getBusinessSite().length() > 500) {
                throw new BaseException("数量超过数据库的存储");
            }
            if (!Strings.isNullOrEmpty(modifyLspInfoBO.getName()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyLspInfoBO.getName()))
                    throw new BaseException("承运商名称不合法");
            if (!Strings.isNullOrEmpty(modifyLspInfoBO.getLegalRep()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyLspInfoBO.getLegalRep()))
                    throw new BaseException("法人姓名不合法");
            if (!Strings.isNullOrEmpty(modifyLspInfoBO.getNameAbbr()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyLspInfoBO.getNameAbbr()))
                    throw new BaseException("简称名不合法");
            Account account = uaaUtil.getLoginAccount();
            Long newTenantId = uaaUtil.createTenant(modifyLspInfoBO.getRepMobile(), modifyLspInfoBO.getName(), modifyLspInfoBO.getTaxpayerId(), authorization);
            BusinessRelation businessRelation = new BusinessRelation();
            businessRelation.setUpperId(account.getTenantId());    //固定为中联物流
            businessRelation.setSupplierId(newTenantId);
            businessRelation.setTenantId(newTenantId);
            EntityWrapper<BusinessRelation> ewBR = new EntityWrapper<>();
            /**
             * 若已存在商业关系，则创建失败
             */
            ewBR
                    .eq("upper_id", businessRelation.getSupplierId())
                    .and()
                    .eq("supplier_id", businessRelation.getSupplierId());
            if (Objects.nonNull(businessRelationService.selectOne(ewBR))) {
                throw new BaseException("商业关系重复，创建失败！");
            }
            businessRelationService.insert(businessRelation);

            /**
             * 数据共享关系（依照商业关系创建）
             */
            Map<String, String> paramsMap = new HashMap<>();
            String owner = String.valueOf(businessRelation.getSupplierId());
            String grantee = String.valueOf(businessRelation.getUpperId());
            paramsMap.put("owner", owner);
            paramsMap.put("grantee", grantee);
            JSONObject obj = JSON.parseObject(HttpClientUtil.post(CREATE_TENANT_SHARING_RULE_URI, paramsMap,
                    10000));
            if (obj.getIntValue("code") != 0) {
                throw new BaseException("数据重复，创建失败！");
            }
            // 添加承运商基础信息

            BeanUtils.copyProperties(modifyLspInfoBO, lspInfo);
            lspInfo.setCode(String.valueOf(new Date().getTime()));
            lspInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
            lspInfo.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
            lspInfo.setCreateFrom(SourceEnum.LSPM.getText());
            lspInfo.setGmtCreate(new Date());
            lspInfo.setGmtUpdate(new Date());
            lspInfo.setCreator(uaaUtil.getLoginAccountNo());
            lspInfo.setTenantId(new Long(newTenantId));
            this.insert(lspInfo);
            List<ModifyLspLicenseBO> licenseBOList = modifyLspInfoBO.getModifyLspLicenseBOList();
            for (ModifyLspLicenseBO licenseBO : licenseBOList) {
                LspLicense license = new LspLicense();
                BeanUtils.copyProperties(licenseBO, license);
                license.setLspId(lspInfo.getId());
                lspLicenseService.insert(license);
            }

            // 添加承运商银行卡信息
            List<ModifyLspBankAccountBO> modifyLspBankAccountBOList = modifyLspInfoBO.getModifyLspBankAccountBOList();
            List<LspBankAccount> lspBankAccountList = new ArrayList<>();
            for (ModifyLspBankAccountBO modifyLspBankAccountBO : modifyLspBankAccountBOList) {
                LspBankAccount lspBankAccount = new LspBankAccount();
                BeanUtils.copyProperties(modifyLspBankAccountBO, lspBankAccount);
                lspBankAccount.setLspId(lspInfo.getId());
                lspBankAccountList.add(lspBankAccount);
            }
            if (!CollectionUtils.isEmpty(lspBankAccountList)) {
                lspBankAccountService.insertBatch(lspBankAccountList);
            }

            // 添加承运商油卡信息
            List<ModifyLspCardBO> modifyLspCardBOList = modifyLspInfoBO.getModifyLspCardBOList();
            List<LspCard> lspCardList = new ArrayList<>();
            for (ModifyLspCardBO modifyLspCardBO : modifyLspCardBOList) {
                LspCard lspCard = new LspCard();
                BeanUtils.copyProperties(modifyLspCardBO, lspCard);
                lspCard.setLspId(lspInfo.getId());
                lspCardList.add(lspCard);
            }
            if (!CollectionUtils.isEmpty(lspCardList)) {
                lspCardService.insertBatch(lspCardList);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception ex) {
            throw new BaseException(-1, "操作异常请重试");
        }
    }


    private LspLicense getLicenseByIdOrType(ModifyLspLicenseBO modifyLspLicenseBO, Long lspId) {
        LspLicense license = new LspLicense();
        if (Objects.isNull(license.getId())) {
            EntityWrapper<LspLicense> ew = new EntityWrapper<>();
            ew.eq("lsp_id", lspId);
            ew.eq("license_type_id", modifyLspLicenseBO.getLicenseTypeId());
            List<LspLicense> lspLicenses = lspLicenseService.selectList(ew);
            if (!CollectionUtils.isEmpty(lspLicenses)) {
                license = lspLicenses.get(0);
            }
        } else {
            EntityWrapper<LspLicense> ew = new EntityWrapper<>();
            ew.eq("id", modifyLspLicenseBO.getId());
            List<LspLicense> lspLicenses = lspLicenseService.selectList(ew);
            if (!CollectionUtils.isEmpty(lspLicenses)) {
                license = lspLicenses.get(0);
            }
        }
        return license;
    }

    @Override
    public void updateLicense(ModifyLspInfoBO modifyLspInfoBO) {
        if (Objects.isNull(modifyLspInfoBO.getId())) throw new BaseException("未绑定承运商");
        List<ModifyLspLicenseBO> toLspLicenseList = modifyLspInfoBO.getModifyLspLicenseBOList();
        toLspLicenseList.forEach(modifyLspLicenseBO -> {
            LspLicense license = new LspLicense();
            BeanUtils.copyProperties(modifyLspLicenseBO, license);
            license.setId(getLicenseByIdOrType(modifyLspLicenseBO, modifyLspInfoBO.getId()).getId());
            if (Objects.isNull(license.getId())) {
                license.setLspId(modifyLspInfoBO.getId());
                lspLicenseService.insert(license);
                // 添加承运商证照附件
                List<LspLicenseAttach> lspLicenseAttaches = modifyLspLicenseBO.getLicenseAttachList();
                for (LspLicenseAttach lspLicenseAttache :
                        lspLicenseAttaches) {
                    lspLicenseAttache.setLspId(modifyLspInfoBO.getId());
                    lspLicenseAttache.setLicenseId(license.getId());
                }
                if (!CollectionUtils.isEmpty(lspLicenseAttaches))
                    licenseAttachService.insertBatch(lspLicenseAttaches);
            } else {
                for (LspLicenseAttach lspLicenseAttach :
                        modifyLspLicenseBO.getLicenseAttachList()) {
                    //删除原有附件
                    EntityWrapper<LspLicenseAttach> ewAttach = new EntityWrapper<>();
                    ewAttach.eq("lsp_id", modifyLspInfoBO.getId());
                    ewAttach.eq("license_id", license.getId());
                    ewAttach.eq("attach_type", lspLicenseAttach.getAttachType());
                    //获取对应承运商现有证照的附件信息
                    LspLicenseAttach licenseAttach = licenseAttachService.selectOne(ewAttach);
                    //若存在附件
                    if (Objects.nonNull(licenseAttach)) {
                        //和本次上传的附件不一样，软删之后在新增，不一样直接跳过本次新增
                        if (!lspLicenseAttach.getAttachKey().equals(licenseAttach.getAttachKey())) {
                            licenseAttachService.updateOldAttachDeleteState(licenseAttach);
                        } else {
                            continue;
                        }
                    }
                    //修改附件对应信息，写入库
                    lspLicenseAttach.setLspId(modifyLspInfoBO.getId());
                    lspLicenseAttach.setLicenseId(license.getId());
                    licenseAttachService.insert(lspLicenseAttach);
                }
            }
        });
    }

    @Override
    public void deleteLicense(ModifyLspLicenseBO modifyLspLicenseBO) {
//        EntityWrapper<LspLicenseAttach> ewAttach = new EntityWrapper<>();
//        ewAttach.eq("id", lspLicenseAttach.getId());
//        ewAttach.eq("is_delete", "0");
//        licenseAttachService.updateDeleteState(ewAttach);


        for (LspLicenseAttach lspLicenseAttach :
                modifyLspLicenseBO.getLicenseAttachList()) {
            if (Objects.isNull(lspLicenseAttach.getId())) {
                EntityWrapper<LspLicense> ew = new EntityWrapper<>();
                ew.eq("license_type_id", modifyLspLicenseBO.getLicenseTypeId());
                ew.eq("lsp_id", modifyLspLicenseBO.getLspId());
                List<LspLicense> lspLicenses = lspLicenseService.selectList(ew);
                if (CollectionUtils.isEmpty(lspLicenses)) throw new BaseException("未查找到匹配删除项");
                EntityWrapper<LspLicenseAttach> ewAttach = new EntityWrapper<>();
                LspLicense lspLicense = lspLicenses.get(0);
                ewAttach.eq("lsp_id", modifyLspLicenseBO.getLspId());
                ewAttach.eq("license_id", lspLicense.getId());
                ewAttach.eq("attach_type", lspLicenseAttach.getAttachType());
//                ewAttach.eq("is_delete", "0");
//                licenseAttachService.updateDeleteState(ewAttach);
                LspLicenseAttach licenseAttach = licenseAttachService.selectOne(ewAttach);
                if (Objects.nonNull(licenseAttach)) {
                    licenseAttachService.updateOldAttachDeleteState(licenseAttach);
                }
            } else {
                EntityWrapper<LspLicenseAttach> ewAttach = new EntityWrapper<>();
                ewAttach.eq("id", lspLicenseAttach.getId());
//                ewAttach.eq("is_delete", "0");
//                licenseAttachService.updateDeleteState(ewAttach);
                LspLicenseAttach licenseAttach = licenseAttachService.selectOne(ewAttach);
                if (Objects.nonNull(licenseAttach)) {
                    licenseAttachService.updateOldAttachDeleteState(licenseAttach);
                }
            }
        }
    }


    @Override
    public ModifyLspInfoBO findByCode(String code) {

        if (code == null)
            return null;

        ModifyLspInfoBO modifyLspInfoBO = new ModifyLspInfoBO();

        // 查询编辑承运商信息
        Wrapper<LspInfo> lspEntity = new EntityWrapper<>();
        lspEntity.eq("code", code);
        List<LspInfo> lspInfoList = this.selectList(lspEntity);
        if (CollectionUtils.isEmpty(lspInfoList))
            throw new BaseException("承运商不存在");

        LspInfo lspInfo = lspInfoList.get(0);

        BeanUtils.copyProperties(lspInfo, modifyLspInfoBO);

        //承运商的证照信息
        List<ModifyLspLicenseBO> modifyLspLicenseVOList = findLicenseById(lspInfo.getId());
        modifyLspInfoBO.setModifyLspLicenseBOList(modifyLspLicenseVOList);

        // 获取承运商下的油卡信息
        List<ModifyLspCardBO> modifyLspCardBOList = lspCardService.findByLspId(lspInfo.getId());
        modifyLspInfoBO.setModifyLspCardBOList(modifyLspCardBOList);

        // 获取承运商下的银行卡信息
        List<ModifyLspBankAccountBO> modifyLspBankAccountBOList = lspBankAccountService.findByLspId(lspInfo.getId());
        modifyLspInfoBO.setModifyLspBankAccountBOList(modifyLspBankAccountBOList);

        return modifyLspInfoBO;
    }

    @Override
    public ModifyLspInfoBO findModifyInfo(Long id) {

        if (id == null)
            return null;

        // 查询编辑承运商信息
        LspInfo lspInfo = this.selectById(id);
        if (lspInfo == null)
            return null;

        ModifyLspInfoBO modifyLspInfoBO = new ModifyLspInfoBO();

        BeanUtils.copyProperties(lspInfo, modifyLspInfoBO);

        // 获取承运商下的证照
        List<ModifyLspLicenseBO> modifyLspLicenseVOList = findLicenseById(lspInfo.getId());
        if (!CollectionUtils.isEmpty(modifyLspLicenseVOList)) {
            modifyLspInfoBO.setModifyLspLicenseBOList(modifyLspLicenseVOList);
        }
        EntityWrapper<LspLicense> ew = new EntityWrapper<>();
        LicenseTypeVo licenseTypeVo = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.LSP_TAX_ID.getCode(), SubjectTypeEnum.LSP.getCode());
        if (Objects.nonNull(licenseTypeVo))
            ew.eq("lsp_id", lspInfo.getId()).eq("license_type_id", licenseTypeVo.getId());
        List<LspLicense> lspLicenses = lspLicenseService.selectList(ew);
        if (!CollectionUtils.isEmpty(lspLicenses)) {
            modifyLspInfoBO.setTaxpayerId(lspLicenses.get(0).getLicenseId());
        }
        // 获取承运商下的油卡信息
        List<ModifyLspCardBO> modifyLspCardBOList = lspCardService.findByLspId(id);
        if (!CollectionUtils.isEmpty(modifyLspCardBOList)) {
            modifyLspCardBOList.forEach(
                    modifyLspCardBO ->
                            modifyLspCardBO.setIssuerTypeName(
                                    mdmUtil.getCardIssuerTypeNameById(modifyLspCardBO.getIssuerType())));
        }
        modifyLspInfoBO.setModifyLspCardBOList(modifyLspCardBOList);

        // 获取承运商下的银行卡信息
        List<ModifyLspBankAccountBO> modifyLspBankAccountBOList = lspBankAccountService.findByLspId(id);
        modifyLspInfoBO.setModifyLspBankAccountBOList(modifyLspBankAccountBOList);

        //返回服务类型名称
        modifyLspInfoBO.setServiceTypeName(mdmUtil.getServiceTypeByCodes(modifyLspInfoBO.getServiceType()));


        return modifyLspInfoBO;
    }

    @Override
    public List<ModifyLspLicenseBO> findLicenseById(Long id) {

        if (Objects.isNull(id))
            throw new BaseException("缺少承运商");

        //是否存在附件
        Boolean isHaveAttach = false;
        List<ModifyLspLicenseBO> modifyLspLicenseBOList = new ArrayList<>();


        // 查找承运商的证照信息
        Wrapper<LspLicense> licenseEntity = new EntityWrapper<>();
        licenseEntity.eq("lsp_id", id);
        List<LspLicense> licenseList = lspLicenseService.selectList(licenseEntity);
        if (!CollectionUtils.isEmpty(licenseList)) {
            for (LspLicense license : licenseList) {
                ModifyLspLicenseBO modifyLspLicenseBO = new ModifyLspLicenseBO();
                BeanUtils.copyProperties(license, modifyLspLicenseBO);

                // 查找证照的附件信息
                Wrapper<LspLicenseAttach> licenseAttachEntity = new EntityWrapper<>();
                licenseAttachEntity.eq("license_id", license.getId()).eq("lsp_id", license.getLspId());
                List<LspLicenseAttach> lspLicenseAttachList = licenseAttachService.selectList(licenseAttachEntity);
                if (!CollectionUtils.isEmpty(lspLicenseAttachList)) {
                    modifyLspLicenseBO.setLicenseAttachList(lspLicenseAttachList);
                    isHaveAttach = true;
                }

                //证照的有效状态判断
                modifyLspLicenseBO.setStatus(getValidStatus(license, isHaveAttach));
                modifyLspLicenseBOList.add(modifyLspLicenseBO);
            }
        }

        return modifyLspLicenseBOList;
    }

    @Transactional
    @Override
    public void modifyLspInfo(ModifyLspInfoBO modifyLspInfoBO, String authorization) throws BaseException {
        try {
            // 校验数据
            checkModifyData(modifyLspInfoBO, "modify");

            if (modifyLspInfoBO.getBusinessSite() != null
                    && modifyLspInfoBO.getBusinessSite().length() > 500) {
                throw new BaseException("业务覆盖城市太长");
            }
            if (!Strings.isNullOrEmpty(modifyLspInfoBO.getName()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyLspInfoBO.getName()))
                    throw new BaseException("承运商名称不合法");
            if (!Strings.isNullOrEmpty(modifyLspInfoBO.getLegalRep()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyLspInfoBO.getLegalRep()))
                    throw new BaseException("法人姓名不合法");
            if (!Strings.isNullOrEmpty(modifyLspInfoBO.getNameAbbr()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyLspInfoBO.getNameAbbr()))
                    throw new BaseException("简称名不合法");
            //判断名称是否修改
            LspInfo lspInfoByBo = null;
            if (!Objects.isNull(modifyLspInfoBO.getId())) {
                lspInfoByBo = selectById(modifyLspInfoBO.getId());
                if (modifyLspInfoBO.getName().equals(lspInfoByBo.getName())) lspInfoByBo = null;
            }
            // 更新承运商基础信息
            LspInfo lspInfo = new LspInfo();
            BeanUtils.copyProperties(modifyLspInfoBO, lspInfo);
            Integer authStatus = lspInfo.getAuthStatus();
            if (AuthStatusEnum.CERTIFICATION.getCode().equals(authStatus)) {
                throw new BaseException(-1, "该承运商已经认证，请取消认证后再进行修改");
            }

            lspInfo.setGmtUpdate(new Date());
            this.updateById(lspInfo);
            if (!Objects.isNull(lspInfoByBo))
                uaaUtil.updateCorpName(lspInfoByBo.getTenantId(), modifyLspInfoBO.getName(), authorization);
            // 查询承运商名称是否已经存在


            // 查询承运商简称是否已经存在
            Wrapper<LspInfo> lspNameAbbrEntity = new EntityWrapper<>();
            lspNameAbbrEntity.eq("name", modifyLspInfoBO.getName());
            List<LspInfo> lspNameAbbrList = this.selectList(lspNameAbbrEntity);
            if (lspNameAbbrList.size() > 1)
                throw new BaseException(LspEnum.LSP_NAMEABBR_EXIST.getCode(), LspEnum.LSP_NAMEABBR_EXIST.getText());

            // 查询承运商下的证照
            Wrapper<LspLicense> driverLicenseEntity = new EntityWrapper<>();
            driverLicenseEntity.eq("lsp_id", lspInfo.getId());
            List<LspLicense> selectLspLicenseList = lspLicenseService.selectList(driverLicenseEntity);
            // 前端传送的证照
            List<ModifyLspLicenseBO> toLspLicenseList = modifyLspInfoBO.getModifyLspLicenseBOList();

            if (CollectionUtils.isEmpty(selectLspLicenseList)) {
                //原来没有证照
                toLspLicenseList.forEach(modifyLspLicenseBO -> {
                    LspLicense license = new LspLicense();
                    BeanUtils.copyProperties(modifyLspLicenseBO, license);
                    license.setLspId(lspInfo.getId());
                    lspLicenseService.insert(license);
                });
            } else {
                toLspLicenseList.forEach(modifyLspLicenseBO -> {
                    LspLicense license = new LspLicense();
                    BeanUtils.copyProperties(modifyLspLicenseBO, license);
                    license.setId(getLicenseByIdOrType(modifyLspLicenseBO, modifyLspInfoBO.getId()).getId());
                    if (Objects.isNull(license.getId())) {
                        //新增
                        license.setLspId(lspInfo.getId());
                        lspLicenseService.insert(license);
                    } else {
                        //更新
                        lspLicenseService.updateById(license);
                    }
                });
            }


            // 前端传送的银行卡信息
            List<ModifyLspBankAccountBO> toLspBankAccountList = modifyLspInfoBO.getModifyLspBankAccountBOList();
            // 前端添加的银行卡信息
            List<LspBankAccount> addLspBankAccountList = new ArrayList<>();
            // 前端传送的油卡信息
            List<ModifyLspCardBO> toLspCardList = modifyLspInfoBO.getModifyLspCardBOList();
            // 前端添加的油卡信息
            List<LspCard> addLspCardList = new ArrayList<>();


            // 更新承运商银行卡信息
            for (ModifyLspBankAccountBO toLspBankAccount : toLspBankAccountList) {
                LspBankAccount lspBankAccount = new LspBankAccount();
                BeanUtils.copyProperties(toLspBankAccount, lspBankAccount);
                if (toLspBankAccount.getId() == null) {
                    lspBankAccount.setLspId(lspInfo.getId());
                    addLspBankAccountList.add(lspBankAccount);
                } else {
                    lspBankAccountService.updateById(lspBankAccount);
                }
            }

            // 更新承运商油卡信息
            for (ModifyLspCardBO toLspCard : toLspCardList) {
                LspCard lspCard = new LspCard();
                BeanUtils.copyProperties(toLspCard, lspCard);
                if (toLspCard.getId() == null) {
                    lspCard.setLspId(lspInfo.getId());
                    addLspCardList.add(lspCard);
                } else {
                    lspCardService.updateById(lspCard);
                }
            }

            if (!CollectionUtils.isEmpty(addLspBankAccountList)) {
                // 批量添加银行卡信息
                lspBankAccountService.insertOrUpdateBatch(addLspBankAccountList);
            }
            if (!CollectionUtils.isEmpty(addLspCardList)) {
                lspCardService.insertOrUpdateBatch(addLspCardList);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception ex) {
            throw new BaseException(-1, "操作异常请重试");
        }
    }

    @Override
    public void checkModifyData(ModifyLspInfoBO modifyLspInfoBO, String operate) {

        if (modifyLspInfoBO == null || StringUtils.isEmpty(operate))
            return;
        if (operate.equals("modify")) {
            if (modifyLspInfoBO.getId() == null)
                return;
            Wrapper<LspInfo> lspNameEntity = new EntityWrapper<>();
            lspNameEntity.ne("id", modifyLspInfoBO.getId()).andNew()
                    .eq("name", modifyLspInfoBO.getName())
                    .or()
                    .eq("name_abbr", modifyLspInfoBO.getNameAbbr());
            List<LspInfo> lspNameList = baseMapper.selectListNoTenant(lspNameEntity);
            if (!CollectionUtils.isEmpty(lspNameList))
                throw new BaseException(LspEnum.LSP_NAME_EXIST.getCode(), LspEnum.LSP_NAME_EXIST.getText());
        }

        if (modifyLspInfoBO == null)
            return;

        if (operate.equals("insert")) {
            // 查询承运商名称是否已经存在
            Wrapper<LspInfo> lspNameEntity = new EntityWrapper<>();
            lspNameEntity
                    .eq("name", modifyLspInfoBO.getName())
                    .or()
                    .eq("name_abbr", modifyLspInfoBO.getNameAbbr());
            List<LspInfo> lspNameList = baseMapper.selectListNoTenant(lspNameEntity);
            if (!CollectionUtils.isEmpty(lspNameList))
                throw new BaseException(LspEnum.LSP_NAME_EXIST.getCode(), LspEnum.LSP_NAME_EXIST.getText());

//            // 查询承运商简称是否已经存在
//            Wrapper<LspInfo> lspNameAbbrEntity = new EntityWrapper<>();
//            lspNameAbbrEntity.eq("name", modifyLspInfoBO.getName());
//            List<LspInfo> lspNameAbbrList = this.selectList(lspNameAbbrEntity);
//            if (!CollectionUtils.isEmpty(lspNameAbbrList))
//                throw new BaseException(LspEnum.LSP_NAMEABBR_EXIST.getCode(), LspEnum.LSP_NAMEABBR_EXIST.getText());
        }
    }

    @Transactional
    public void lisAuth(Long lspId) throws BaseException {
        LspInfo lspInfo = this.selectById(lspId);
        List<Long> lspIds = new ArrayList<>();
        if (Objects.isNull(lspInfo)) throw new BaseException("承运商不存在");
        if (lspInfo.getAuthStatus().equals(AuthStatusEnum.CERTIFICATION.getCode())) {
            throw new BaseException("承运商:" + lspInfo.getName() + ":" + "已经是认证状态，无需重复进行认证");
        }
//        try {
//            licenseValid(lspId);//校验证照
//        } catch (BaseException e) {
//            throw new BaseException("承运商:" + lspInfo.getName() + ":" + e.getMessage());
//        }

        lspIds.add(lspId);

        LspAuditLog lspAuditLog = new LspAuditLog();
        lspAuditLog.setLspId(lspId);
        lspAuditLog.setAuditResult(1);
        JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
        if (Objects.nonNull(jwtAccountVO)) {
            lspAuditLog.setTenantId(Long.parseLong(jwtAccountVO.getTenantId()));
            lspAuditLog.setCreator(jwtAccountVO.getAccountId());
        }
        baseMapper.batchUpdateStatus(AuthStatusEnum.CERTIFICATION.getCode(),
                StatusEnum.ENABLE.getCode(), lspIds); //认证承运商
        lspAuditLogService.insert(lspAuditLog); //保存认证日志
        if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
            replaceServiceType(lspInfo);
            LspInfoDTO lspInfoDTO = new LspInfoDTO();
            BeanUtils.copyProperties(lspInfo, lspInfoDTO);
            lspInfoDTO.setIsActive("Y");
            integrationUtil.exportLspToOTM(lspInfoDTO);
        }
    }

    public LspInfo replaceServiceType(LspInfo lspInfo) {
        // 服务类型
        if (!StringUtils.isEmpty(lspInfo.getServiceType())) {
            if (!StringUtils.isEmpty(lspInfo.getServiceType())) {
                List<TransportationTypeVO> allServiceType = mdmUtil.getAllTransportType();
                String serviceTypeName = lspInfo.getServiceType();
                for (TransportationTypeVO transportationTypeVO :
                        allServiceType) {
                    serviceTypeName = serviceTypeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getTosCode());
                }
                lspInfo.setServiceType(serviceTypeName);
            }
            String serviceType = mdmUtil.getServiceTypeByCodes(lspInfo.getServiceType());
            lspInfo.setServiceType(integrationUtil.getServiceType(serviceType));
        }
        return lspInfo;
    }

    @Override
    public List<String> lspAuth(Long[] lspIds) throws BaseException {

        if (ArrayUtils.isEmpty(lspIds)) throw new BaseException(-1, "参数为空");
        List<String> errorMsg = new ArrayList<>();

        for (Long lspId : lspIds) {
            try {
                lisAuth(lspId);
            } catch (BaseException e) {
                errorMsg.add(e.getMessage());
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
            }
        }
        return errorMsg;
    }

    private boolean licenseValid(Long lspId) throws BaseException {
        EntityWrapper<LspLicense> ew = new EntityWrapper<>();
        ew.eq("lsp_id", lspId);
        List<LspLicense> lspLicenses = lspLicenseService.selectList(ew);
        List<LicenseTypeVo> licenseTypes = mdmUtil.listLicenseTypeBySubject("03");
        for (LspLicense lspLicense : lspLicenses) {
            LicenseTypeVo licenseType = getLicenseType(lspLicense.getLicenseTypeId(), licenseTypes);
            if (Objects.nonNull(licenseType)) {
                if (StringUtils.isEmpty(lspLicense.getLicenseId())) throw new BaseException(
                        licenseType.getTypeValue()
                                + "编码为空");
                Wrapper<LspLicenseAttach> ewAttach = new EntityWrapper<>();
                ewAttach.eq("license_id", lspLicense.getId()).and().eq("lsp_id", lspLicense.getLspId());
                if (licenseAttachService.selectCount(ewAttach) == 0) {
                    throw new BaseException(licenseType.getTypeValue() + "附件为空！");
                }
            } else {
                throw new BaseException("证照类型有误");
            }

        }
        return true;
    }

    private LicenseTypeVo getLicenseType(Long licenseTypeId, List<LicenseTypeVo> licenseTypes) {
        LicenseTypeVo newLicenseType = null;
        Optional<LicenseTypeVo> optional = licenseTypes.stream().filter(licenseType -> licenseType.getId().equals
                (licenseTypeId)).findFirst();
        if (optional.isPresent()) {
            newLicenseType = optional.get();
        }
        return newLicenseType;
    }

    @Transactional
    @Override
    public void cancelAuth(Long[] lspIds) throws BaseException {
        if (ArrayUtils.isEmpty(lspIds)) {
            throw new BaseException(-1, "参数为空");
        }

        try {

            List<Long> lspIdList = Arrays.asList(lspIds);
            List<LspAuditLog> logList = Lists.newArrayList();
            List<LspInfo> lspInfos = Lists.newArrayList();

            if (!CollectionUtils.isEmpty(lspIdList)) {
                lspIdList.forEach(lspId -> {
                    LspInfo lspInfo = this.selectById(lspId);
                    if (Objects.isNull(lspInfo)) {
                        throw new BaseException("承运商不存在");
                    } else {
                        if (lspInfo.getAuthStatus() == AuthStatusEnum.UNAUTHORIZED.getCode()) {
                            throw new BaseException("承运商：" + lspInfo.getName() + "已经是未认证状态，无需在进行取消认证");
                        }
                    }
                    LspAuditLog lspAuditLog = new LspAuditLog();
                    lspAuditLog.setLspId(lspId);
                    lspAuditLog.setAuditResult(0);
                    JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
                    if (Objects.nonNull(jwtAccountVO)) {
                        lspAuditLog.setCreator(jwtAccountVO.getAccountId());
                        lspAuditLog.setTenantId(Long.parseLong(jwtAccountVO.getTenantId()));
                    }
                    logList.add(lspAuditLog);
                    lspInfos.add(lspInfo);
                });

                // 批量更新承运商状态为未认证，并更改业务状态为停用
                baseMapper.batchUpdateStatus(AuthStatusEnum.UNAUTHORIZED.getCode(), StatusEnum.DISCONTINUAT.getCode()
                        , lspIdList);
                if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
                    for (LspInfo lspInfo :
                            lspInfos) {
                        LspInfoDTO lspInfoDTO = new LspInfoDTO();
                        BeanUtils.copyProperties(replaceServiceType(lspInfo), lspInfoDTO);
                        lspInfoDTO.setIsActive("N");
                        integrationUtil.exportLspToOTM(lspInfoDTO);
                    }
                }
            }

            if (!CollectionUtils.isEmpty(logList)) {
                // 批量插入承运商认证记录
                lspAuditLogService.batchInsert(logList);
            }

            // 获取所有承运商下的牵引车 id
            List<Long> carrierIdList = carrierInfoService.selectIdByLspIds(lspIdList);
            if (!CollectionUtils.isEmpty(carrierIdList)) {
                // 取消承运商底下的牵引车认证
                carrierInfoService.batchUpdateAuthStatusByIds(AuthStatusEnum.UNAUTHORIZED.getCode(), StatusEnum
                        .DISCONTINUAT.getCode(), carrierIdList);
                carrierAuditLogService.batchInsertLog(carrierIdList, 0);
            }

            // 获取所有承运商下的挂车 id
            List<Long> trailerIdList = trailerInfoService.selectIdByLspIds(Arrays.asList(lspIds));
            if (!CollectionUtils.isEmpty(trailerIdList)) {
                // 取消承运商底下的挂车认证
                trailerInfoService.batchUpdateAuthStatusByIds(AuthStatusEnum.UNAUTHORIZED.getCode(), StatusEnum
                        .DISCONTINUAT.getCode(), trailerIdList);
                trailerAuditLogService.batchInsertLog(trailerIdList, AuthStatusEnum.UNAUTHORIZED.getCode
                        ());
            }
            if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
                for (Long carrierId :
                        carrierIdList) {
                    WeChatVehicle weChatVehicle = carrierInfoService.selectVehicleByCarrierIdOrTrailerId(carrierId, null);
                    exporVehicleToOTM(weChatVehicle);
                }
            }
            // 获取所有承运商下的司机 id
            List<Long> driverIdList = driverService.selectIdByLspIds(Arrays.asList(lspIds));
            if (!CollectionUtils.isEmpty(driverIdList)) {
                // 取消承运商底下的挂车认证
                driverService.batchUpdateAuthStatusByIds(AuthStatusEnum.UNAUTHORIZED.getCode(), StatusEnum
                        .DISCONTINUAT.getCode(), driverIdList);
                if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
                    for (Long driverId :
                            driverIdList) {
                        DriverDTO driverDTO = new DriverDTO();
                        BeanUtils.copyProperties(driverService.selectById(driverId), driverDTO);
                        driverDTO.setIsActive("N");
                        integrationUtil.exportDriverToOTM(driverDTO);
                    }
                }
                driverAuditLogService.batchInsertLog(driverIdList, AuthStatusEnum.UNAUTHORIZED.getCode());
            }
        } catch (Exception ex) {
            throw new BaseException(-1, ex.getMessage());
        }

    }

    private void exporVehicleToOTM(WeChatVehicle weChatVehicle) {
        if (!StringUtils.isEmpty(weChatVehicle.getTrailerTypeId()) && weChatVehicle.getAuthStatus() == 0 && weChatVehicle.getTrailerAuthStatus() == 0) {
            String trailerTypeName = mdmUtil.getTransportTypeByCode(weChatVehicle.getTrailerTypeId()).getValue();
            weChatVehicle.setTrailerTypeName(integrationUtil.getTrailerTypeName(trailerTypeName));
            VehicleDTO vehicleDTO = new VehicleDTO();
            BeanUtils.copyProperties(weChatVehicle, vehicleDTO);
            integrationUtil.exportVehicleToOTM(vehicleDTO);
        }
    }

    @Override
    public List<LspInfo> vagueSelectLsp(String name) {
        Wrapper<LspInfo> ew = new EntityWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            ew.like("name", name);
        }
        return this.selectList(ew);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void discontinuatLsps(Long[] lspIds) throws BaseException {

        try {
            if (ArrayUtils.isEmpty(lspIds)) {
                throw new BaseException(-1, "参数为空");
            }

            List<Long> lspIdList = Arrays.asList(lspIds);
            lspIdList.forEach(lspId -> {
                // 更新承运商状态
                LspInfo lspInfo = this.selectById(lspId);
                if (lspInfo.getStatus() == StatusEnum.DISCONTINUAT.getCode()) {
                    throw new BaseException("承运商：" + lspInfo.getName() + "已经被停用，无需在进行停用");
                }

                lspInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
                this.updateById(lspInfo);

                //// 停用承运商下的牵引车
                //CarrierInfo carrierInfo = new CarrierInfo();
                //carrierInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
                //EntityWrapper<CarrierInfo> carrierEntity = new EntityWrapper<>();
                //carrierEntity.eq("lsp_id", lspId);
                //carrierInfoService.update(carrierInfo, carrierEntity);
                //
                //// 停用承运商下的挂车
                //TrailerInfo trailerInfo = new TrailerInfo();
                //trailerInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
                //EntityWrapper<TrailerInfo> trailerEntity = new EntityWrapper<>();
                //trailerEntity.eq("lsp_id", lspId);
                //trailerInfoService.update(trailerInfo, trailerEntity);
                //
                //// 停用承运商下的司机
                //Driver driver = new Driver();
                //driver.setStatus(StatusEnum.DISCONTINUAT.getCode());
                //EntityWrapper<Driver> driverEntity = new EntityWrapper<>();
                //driverEntity.eq("lsp_id", lspId);
                //driverService.update(driver, driverEntity);
            });
        } catch (Exception ex) {
            throw new BaseException(-1, ex.getMessage());
        }

    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void enableLsps(Long[] lspIds) {

        try {
            if (ArrayUtils.isEmpty(lspIds)) {
                throw new BaseException(-1, "参数为空");
            }
            List<Long> lspIdList = Arrays.asList(lspIds);
            lspIdList.forEach(lspId -> {
                LspInfo lspInfo = this.selectById(lspId);
                if (lspInfo.getStatus() == StatusEnum.ENABLE.getCode()) {
                    throw new BaseException("承运商：" + lspInfo.getName() + "已经启用，无需再进行启用");
                }
                lspInfo.setStatus(StatusEnum.ENABLE.getCode());
                this.updateById(lspInfo);

                // 启用承运商下的牵引车
                CarrierInfo carrierInfo = new CarrierInfo();
                carrierInfo.setStatus(StatusEnum.ENABLE.getCode());
                EntityWrapper<CarrierInfo> carrierEntity = new EntityWrapper<>();
                carrierEntity.eq("lsp_id", lspId);
                carrierInfoService.update(carrierInfo, carrierEntity);

                // 启用承运商下的挂车
                TrailerInfo trailerInfo = new TrailerInfo();
                trailerInfo.setStatus(StatusEnum.ENABLE.getCode());
                EntityWrapper<TrailerInfo> trailerEntity = new EntityWrapper<>();
                trailerEntity.eq("lsp_id", lspId);
                trailerInfoService.update(trailerInfo, trailerEntity);

                // 启用承运商下的司机
                Driver driver = new Driver();
                driver.setStatus(StatusEnum.ENABLE.getCode());
                EntityWrapper<Driver> driverEntity = new EntityWrapper<>();
                driverEntity.eq("lsp_id", lspId);
                driverService.update(driver, driverEntity);
            });
        } catch (Exception ex) {
            throw new BaseException(-1, ex.getMessage());
        }
    }

    //构建查询条件
    private EntityWrapper<AfterAuthLspLineBO> buildCondition(Map<String, Object> condition) {
        EntityWrapper<AfterAuthLspLineBO> ew = new EntityWrapper<>();
        if (!Objects.equals(condition, null)) {
            for (Map.Entry<String, Object> entry : condition.entrySet()) {
                if (!StringUtils.isEmpty(entry.getValue().toString())) {
                    // 承运商名称
                    if (entry.getKey().equals("name")) {
                        ew.like("name", entry.getValue().toString());
                    }
                    // 服务类型
                    if (entry.getKey().equals("serviceType")) {
                        ew.like("service_type", entry.getValue().toString());
                    }
                    //业务状态
                    if (entry.getKey().equals("status")) {
                        ew.eq("status", entry.getValue().toString());
                    }
                    // 认证状态
                    if (entry.getKey().equals("authStatus")) {
                        ew.eq("auth_status", entry.getValue().toString());
                    }
                }
            }
        }
        return ew;
    }

    //构建承运商注册查询条件
    private EntityWrapper<LspInfoLineVO> buildConditionInfo(Map<String, Object> condition) {
        EntityWrapper<LspInfoLineVO> ew = new EntityWrapper<>();
        if (!Objects.equals(condition, null)) {
            for (Map.Entry<String, Object> entry : condition.entrySet()) {
                if (!StringUtils.isEmpty(entry.getValue().toString())) {
                    // 承运商名称
                    if (entry.getKey().equals("name")) {
                        ew.like("name", entry.getValue().toString());
                    }
                    //业务状态
                    if (entry.getKey().equals("status")) {
                        ew.eq("status", entry.getValue().toString());
                    }
                    if (entry.getKey().equals("status")) {
                        ew.eq("status", entry.getValue().toString());
                    }
                    if (entry.getKey().equals("canDel")) {
                        if (StringUtils.isEmpty(entry.getValue())) {
                            ew.eq("is_delete", 0);
                        } else {
                            ew.eq("is_delete", entry.getValue().toString());
                        }
                    }
                }
            }
        }
        JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
        if (Objects.isNull(jwtAccountVO)) throw new BaseException("请绑定登陆信息");
        ew.andNew().ne("name", jwtAccountVO.getCorpName()).or().ne("tenant_id", jwtAccountVO.getTenantId());
        ew.orderBy("gmt_create", false);
        return ew;
    }

    //构建认证承运商查询条件
    private EntityWrapper<LspAuthLineBO> buildConditionLspAuthLineBO(Map<String, Object> condition) {
        EntityWrapper<LspAuthLineBO> ew = new EntityWrapper<>();
        if (!Objects.equals(condition, null)) {
            // 牵引车认证状态
            if (TableStatusEnum.STATUS_1.getCode().equals(condition.get("authedCarrier"))) {
                ew.gt("authedCarrierCount", 0);
            }
            if (TableStatusEnum.STATUS_0.getCode().equals(condition.get("authedCarrier"))) {
                ew.gt("noAuthCarrierCount", 0);
            }
            // 挂车认证状态
            if (TableStatusEnum.STATUS_1.getCode().equals(condition.get("authedTrailer"))) {
                ew.gt("authedTrailerCount", 0);
            }
            if (TableStatusEnum.STATUS_0.getCode().equals(condition.get("authedTrailer"))) {
                ew.gt("noAuthTrailerCount", 0);
            }
            // 司机认证状态
            if (TableStatusEnum.STATUS_1.getCode().equals(condition.get("authedDriver"))) {
                ew.gt("authedDriverCount", 0);
            }
            if (TableStatusEnum.STATUS_0.getCode().equals(condition.get("authedDriver"))) {
                ew.gt("noAuthDriverCount", 0);
            }
            for (Map.Entry<String, Object> entry : condition.entrySet()) {
                if (!StringUtils.isEmpty(entry.getValue().toString())) {
                    // 承运商名称
                    if (entry.getKey().equals("name")) {
                        ew.like("name", entry.getValue().toString());
                    }
                    // 服务类型
                    if (entry.getKey().equals("serviceType")) {
                        ew.like("service_type", entry.getValue().toString());
                    }
                    //业务状态
                    if (entry.getKey().equals("status")) {
                        ew.eq("status", entry.getValue().toString());
                    }
                    // 承运商认证状态
                    if (entry.getKey().equals("authStatus")) {
                        ew.eq("auth_status", entry.getValue().toString());
                    }
                }

            }
        }
        //获取当前登录用户的信息
        Account account = uaaUtil.getLoginAccount();
        //ew.ne("tenant_id", account.getTenantId());
        ew.orderBy("id", false);
        return ew;
    }


    /**
     * 得到证照的状态
     *
     * @param lspLicense
     * @return
     */
    private Integer getValidStatus(LspLicense lspLicense, Boolean isHaveAttach) {

        if (Objects.isNull(isHaveAttach)) {
            // 查找证照的附件信息
            Wrapper<LspLicenseAttach> licenseAttachEntity = new EntityWrapper<>();
            licenseAttachEntity.eq("license_id", lspLicense.getId()).eq("lsp_id", lspLicense.getLspId());
            List<LspLicenseAttach> lspLicenseAttachList = licenseAttachService.selectList(licenseAttachEntity);
            if (!CollectionUtils.isEmpty(lspLicenseAttachList)) {
                isHaveAttach = true;
            }
        }

        if (!isHaveAttach) { //无附件
            return LicenseStatusEnum.INVALID.getCode();
        }

        if (Objects.isNull(lspLicense.getGmtReg())) {//无生效时间
            return LicenseStatusEnum.INVALID.getCode();
        }

        if (Objects.isNull(lspLicense.getGmtOverdue())) {//无截止时间
            LicenseTypeVo licenseType = mdmUtil.getLicenseTypeById(lspLicense.getLicenseTypeId().toString());
            if (!licenseType.getIsPerm().equals(1)) {
                return LicenseStatusEnum.INVALID.getCode();
            }
        } else if (!(lspLicense.getGmtOverdue().compareTo(lspLicense.getGmtReg()) >= 0
                && lspLicense.getGmtOverdue().compareTo(new Date()) >= 0)) {
            return LicenseStatusEnum.INVALID.getCode();
        }
        return LicenseStatusEnum.VALID.getCode();
    }

    @Override
    public List<String> deleteByIds(Long[] lspIds, String token) {
        try {
            List<String> msgs = new ArrayList<>();
            for (Long id : lspIds) {
                String msg = "";
                LspInfo lspInfo = this.selectById(id);
                if (AuthStatusEnum.CERTIFICATION.getCode().equals(lspInfo.getAuthStatus())) {
                    msg = "承运商:" + lspInfo.getName() + ":已认证无法删除";
                    msgs.add(msg);
                    continue;
                }

                Wrapper<CarrierInfo> ewCarrier = new EntityWrapper<>();
                ewCarrier.eq("lsp_id", id);
                if (carrierInfoService.selectCount(ewCarrier) > 0) {
                    msg = "承运商:" + lspInfo.getName() + ":存在牵引车，无法删除";
                    msgs.add(msg);
                    continue;
                }

                Wrapper<Driver> ewDriver = new EntityWrapper<>();
                ewDriver.eq("lsp_id", id);
                if (driverService.selectCount(ewDriver) > 0) {
                    msg = "承运商:" + lspInfo.getName() + ":存在司机，无法删除";
                    msgs.add(msg);
                    continue;
                }

                Wrapper<TrailerInfo> ewTrailer = new EntityWrapper<>();
                ewTrailer.eq("lsp_id", id);

                if (trailerInfoService.selectCount(ewTrailer) > 0) {
                    msg = "承运商:" + lspInfo.getName() + ":存在挂车，无法删除";
                    msgs.add(msg);
                    continue;
                }
                if (Objects.nonNull(lspInfo.getTenantId())) {
                    uaaUtil.lockedTenant(lspInfo.getTenantId().toString(), token);
                }
                this.deleteById(id);
            }
            return msgs;
        } catch (Exception e) {
            LOGGER.error("LspInfoServiceImpl.deleteByIds ERROR:" + e.getMessage());
            throw new BaseException("删除承运商错误");
        }
    }


    @Override
    public LspBasicVO getLonginLspInfo() {
        LspInfo lspInfo = this.selectOne(null);
        if (Objects.isNull(lspInfo)) throw new BaseException("无公司信息，请联系管理员");
        LspBasicVO lspBasicVO = new LspBasicVO();
        BeanUtils.copyProperties(lspInfo, lspBasicVO);

        //服务类型处理
        if (!StringUtils.isEmpty(lspInfo.getServiceType())) {
            List<TransportationTypeVO> allServiceType = mdmUtil.getAllTransportType();
            String serviceTypeName = lspInfo.getServiceType();
            for (TransportationTypeVO transportationTypeVO :
                    allServiceType) {
                serviceTypeName = serviceTypeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getValue());
            }
            lspBasicVO.setServiceTypeName(serviceTypeName);
        }
        String creditNo = this.getCreditnoByLspBasic(lspInfo);
        lspBasicVO.setCreditno(creditNo);
        return lspBasicVO;
    }

    @Override
    public Long getLspIdByTenantId(Long tenantId) {
        if (tenantId != null
                && Objects.nonNull(tenantId)) {
            EntityWrapper<LspInfo> lspInfoEntityWrapper = new EntityWrapper<>();
            lspInfoEntityWrapper.eq("tenant_id", tenantId);
            List<LspInfo> lspInfos = this.selectList(lspInfoEntityWrapper);
            if (!(CollectionUtils.isEmpty(lspInfos) || lspInfos.size() == 0)) {
                return lspInfos.get(0).getId();
            }
        }
        return null;
    }

    /**
     * 向mq发送消息
     *
     * @param lspInfo
     * @param taxpayerId
     */
    @Override
    public void lspSendMessage(LspInfo lspInfo, String taxpayerId, Integer isOpenUp, String authorization) {
        LOGGER.info("lspSendMessage parms {}", lspInfo);
        if (StringUtils.isEmpty(taxpayerId)) {
            throw new BaseException("纳税人识别号为空");
        }
        if (StringUtils.isEmpty(lspInfo.getPrincipalMobile()) && StringUtils.isEmpty(lspInfo.getPrincipalEmail())) {
            throw new BaseException("邮箱和手机号至少要填写一个！");
        }
        Destination destination = new ActiveMQQueue(mqNameLsp);
        TenantInfoVO tenantInfoVO = new TenantInfoVO();
        tenantInfoVO.setCorpName(lspInfo.getName());
        tenantInfoVO.setLegalperson(lspInfo.getLegalRep());
        tenantInfoVO.setRegaddress(lspInfo.getRegistrySite());
        tenantInfoVO.setRegcapital(lspInfo.getRegistryCapital());
        tenantInfoVO.setTaxpayerId(taxpayerId);
        tenantInfoVO.setLspId(lspInfo.getId());
        tenantInfoVO.setMobile(lspInfo.getPrincipalMobile());
        tenantInfoVO.setMail(lspInfo.getPrincipalEmail());
        tenantInfoVO.setIsOpenUp(isOpenUp);
        tenantInfoVO.setCreatorTenantId(uaaUtil.getLoginAccount().getTenantId());
        JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
        if (jwtAccountVO != null) {
            tenantInfoVO.setCreator(jwtAccountVO.getAccountId());
        }
        String tenantInfo = JSON.toJSONString(tenantInfoVO);
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        String isOpen = HttpClientUtil.postJson(uaaUrl + tenantIsRegisteredUrl, headNamePairs, tenantInfo, socketTimeout);
        JSONObject jsonObject = JSONObject.parseObject(isOpen);
        if (Boolean.valueOf(jsonObject.get("data").toString())) {
            throw new BaseException("该信息已被注册！");
        }
        User user = new User();
        user.setName(lspInfo.getName());
        user.setLspId(lspInfo.getId());
        user.setMobile(lspInfo.getPrincipalMobile());
        user.setDepartment("lsp");
        user.setCreateUser(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
        user.setModifiedUser(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
        iUserService.addUser(user);
        LOGGER.info("lspSendMessage(mq发送的数据) parms {}", tenantInfo);
        jmsTemplate.convertAndSend(destination, tenantInfo);
    }

    /**
     * 解锁账号
     *
     * @param tenantId
     * @param authorization
     */
    public void unlockAccount(Long tenantId, String authorization) {
        if (StringUtils.isEmpty(tenantId)) throw new BaseException("操作失败！");
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
        Map<String, String> params = new HashMap<>();
        params.put("tenantId", tenantId.toString());
        String reslut = HttpClientUtil.post(uaaUrl + openUpTenantUrl, headNamePairs, params, socketTimeout);
        JSONObject jsonObject = JSONObject.parseObject(reslut);
        if (Integer.valueOf(jsonObject.get("code").toString()) != 0 || jsonObject == null) {
            throw new BaseException("系统异常！");
        }

    }

    @JmsListener(destination = "${mqName.updateLsp}", containerFactory = "jmsListenerContainerQueue")
    @Override
    public void updateTenantId(String tenantLspVO) {
        JSONObject json = JSONObject.parseObject(tenantLspVO);
        TenantLspVO tenantLspVOIfon = json.toJavaObject(TenantLspVO.class);
        //更新承运商租户id
        Wrapper<LspInfo> lspInfoWrapper = new EntityWrapper<>();
        LspInfo lspInfo = new LspInfo();
        lspInfoWrapper.eq("id", tenantLspVOIfon.getLspId());
        lspInfo.setTenantId(tenantLspVOIfon.getTenantId());
        this.update(lspInfo, lspInfoWrapper);
        Account account = uaaUtil.getLoginAccount();
        /**
         *  商业关系
         */
        BusinessRelation businessRelation = new BusinessRelation();
        businessRelation.setUpperId(account.getTenantId());
        businessRelation.setSupplierId(tenantLspVOIfon.getTenantId());
        EntityWrapper<BusinessRelation> ewBR = new EntityWrapper<>();
        JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
        if (jwtAccountVO != null) {
            businessRelation.setCreator(jwtAccountVO.getAccountId());
        }
        /**
         * 若已存在商业关系，则不创建
         */
        ewBR.eq("upper_id", businessRelation.getSupplierId()).and().eq("supplier_id", businessRelation.getSupplierId());
        if (Objects.isNull(businessRelationService.selectOne(ewBR))) {
            businessRelationService.insert(businessRelation);
        }

    }

    @Override
    public Map<String, Object> insertLspInfo(LspCreateLog lspCreateLog) {
        LOGGER.info("接收mq数据创建公司信息", lspCreateLog);
        Map<String, Object> result = new HashMap<>();
        /**
         *  公司基础信息
         */
        LspInfo lspInfo = new LspInfo();
        lspInfo.setCode(String.valueOf(new Date().getTime()));
        lspInfo.setName(lspCreateLog.getName());
        lspInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());          //置为"停用"状态
        lspInfo.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());        //置为"未认证"状态
        lspInfo.setCreateFrom(SourceEnum.WEIXIN.getText());          //数据来源置为"微信"
        lspInfo.setGmtCreate(new Date());
        lspInfo.setGmtUpdate(new Date());

        //公司对应的租户信息
        lspInfo.setTenantId(lspCreateLog.getTenantId());
        lspInfo.setCreator(lspCreateLog.getCreator());

        //公司的基本信息
        lspInfo.setRegistrySite(lspCreateLog.getRegistrySite());
        lspInfo.setLegalRep(lspCreateLog.getLegalRep());

        lspInfo.setRegistryCapital(lspCreateLog.getRegistryCapital());

        Boolean insert = this.insert(lspInfo);

        LspLicense lspLicense = new LspLicense();
        lspLicense.setLicenseId(lspCreateLog.getTaxpayerId());
        lspLicense.setLspId(lspInfo.getId());
        lspLicense.setLicenseTypeId(4L);
        lspLicense.setGmtReg(lspCreateLog.getStartdate());
        lspLicense.setGmtOverdue(lspCreateLog.getEnddate());
        lspLicenseService.insert(lspLicense);
        /**
         *  商业关系
         */
        BusinessRelation businessRelation = new BusinessRelation();
        businessRelation.setUpperId(1L);    //固定为中联物流
        businessRelation.setSupplierId(lspCreateLog.getTenantId());
        businessRelation.setTenantId(lspCreateLog.getTenantId());
        businessRelation.setCreator(lspCreateLog.getCreator());
        EntityWrapper<BusinessRelation> ewBR = new EntityWrapper<>();
        /**
         * 若已存在商业关系，则创建失败
         */
        ewBR
                .eq("upper_id", businessRelation.getSupplierId())
                .and()
                .eq("supplier_id", businessRelation.getSupplierId());
        if (Objects.nonNull(businessRelationService.selectOne(ewBR))) {
            LOGGER.info("registLsp.insertLspInfo 商业关系重复，创建失败");
            throw new BaseException("商业关系重复，创建失败！");
        }
        businessRelationService.insert(businessRelation);
        result.put("isOk", insert);
        result.put("lspId", lspInfo.getId());
        /**
         * 数据共享关系（依照商业关系创建）
         */
        //TODO:移交到uaa那边进行判断
//        Map<String, String> paramsMap = new HashMap<>();
//        String owner = String.valueOf(businessRelation.getSupplierId());
//        String grantee = String.valueOf(businessRelation.getUpperId());
//        paramsMap.put("owner", owner);
//        paramsMap.put("grantee", grantee);
//        JSONObject obj = JSON.parseObject(HttpClientUtil.post(CREATE_TENANT_SHARING_RULE_URI, paramsMap,
//                10000));
//        if (obj.getIntValue("code") != 0) {
//            throw new BaseException("数据重复，创建失败！");
//        }
        User user = new User();
        user.setName(lspInfo.getName());
        user.setLspId(lspInfo.getId());
        user.setMobile(lspInfo.getPrincipalMobile());
        user.setDepartment("lsp");
        user.setCreateUser(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
        user.setModifiedUser(AccountUtil.getAccountInfoFromSecurityContext().getAccountId());
        iUserService.addUser(user);
        return result;
    }


    public void registLsp(TenantInfoVO tenantInfoVO) {
        LOGGER.info("mqRegistLsp params :{}", tenantInfoVO);
        ModifyLspInfoBO modifyLspInfoBO = new ModifyLspInfoBO();

        modifyLspInfoBO.setName(tenantInfoVO.getCorpName());
        // 校验数据
        checkModifyData(modifyLspInfoBO, "insert");
        //注册资本
        // String regcapital = tenantInfoVO.getRegcapital().replace("人民币","").replace("万","").replace("元","").replace("(","").replace(")","").replace("（","").replace("）","").replace(",","").trim();

        //承运商创建日志数据
        LspCreateLog lspCreateLog = new LspCreateLog();
        lspCreateLog.setName(tenantInfoVO.getCorpName());
        lspCreateLog.setTenantId(tenantInfoVO.getTenantId());
        lspCreateLog.setTaxpayerId(tenantInfoVO.getTaxpayerId());
        lspCreateLog.setRegistrySite(tenantInfoVO.getRegaddress());
        lspCreateLog.setLegalRep(tenantInfoVO.getLegalperson());
        lspCreateLog.setRegistryCapital(tenantInfoVO.getRegcapital());
        lspCreateLog.setStartdate(tenantInfoVO.getStartdate());
        lspCreateLog.setEnddate(tenantInfoVO.getEnddate());
        lspCreateLog.setIsSuccess(0);
        lspCreateLog.setTryTimes(0);
        lspCreateLog.setGmtCreate(new Date());
        lspCreateLog.setGmtModify(new Date());
        lspCreateLog.setCreator(tenantInfoVO.getCreator());
        try {
            insertLspInfo(lspCreateLog);
        } catch (BaseException e) {
            LOGGER.error(e.getMessage());
        } catch (Exception e) {
            lspCreateLogService.insert(lspCreateLog);
            new Thread(new Runnable() {
                @Override
                public void run() {
                    for (int i = 0; i < 3; i++) {
                        Map<String, Object> reslut = insertLspInfo(lspCreateLog);
                        System.err.println(reslut);
                        if (Boolean.valueOf(reslut.get("isOk").toString())) {
                            lspCreateLog.setGmtModify(new Date());
                            lspCreateLog.setIsSuccess(1);
                            lspCreateLog.setLspId(reslut.get("lspId").toString());
                            lspCreateLogService.updateById(lspCreateLog);
                            i = 3;
                        } else {
                            lspCreateLog.setTryTimes(i + 1);
                            lspCreateLog.setGmtModify(new Date());
                            lspCreateLogService.updateById(lspCreateLog);
                        }
                    }
                }
            }).start();
        }
    }

    public LspCreateLog LspCreateLogInfo(TenantInfoVO tenantInfoVO) {
        //承运商创建日志数据
        LspCreateLog lspCreateLog = new LspCreateLog();
        lspCreateLog.setName(tenantInfoVO.getCorpName());
        lspCreateLog.setTenantId(tenantInfoVO.getTenantId());
        lspCreateLog.setTaxpayerId(tenantInfoVO.getTaxpayerId());
        lspCreateLog.setRegistrySite(tenantInfoVO.getRegaddress());
        lspCreateLog.setLegalRep(tenantInfoVO.getLegalperson());
        lspCreateLog.setRegistryCapital(tenantInfoVO.getRegcapital());
        lspCreateLog.setStartdate(tenantInfoVO.getStartdate());
        lspCreateLog.setEnddate(tenantInfoVO.getStartdate());
        lspCreateLog.setIsSuccess(0);
        lspCreateLog.setTryTimes(0);
        lspCreateLog.setGmtCreate(new Date());
        lspCreateLog.setGmtModify(new Date());
        lspCreateLogService.insert(lspCreateLog);
        return lspCreateLog;
    }

    /**
     * 更新承运商信息
     *
     * @param lspInfo
     * @param authorization
     * @return
     */
    @Override
    @Transactional
    public LspBasicVO updateLspInfo(LspBasicVO lspInfo, String authorization) {
        try {
            //验证数据
            if (Objects.isNull(lspInfo)) throw new BaseException("请写入承运商信息");
            if (lspInfo.getBusinessSite() != null
                    && lspInfo.getBusinessSite().length() > 500) {
                throw new BaseException("数量超过数据库的存储");
            }
            if (!Strings.isNullOrEmpty(lspInfo.getName()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, lspInfo.getName()))
                    throw new BaseException("承运商名称不合法");

            if (!Strings.isNullOrEmpty(lspInfo.getNameAbbr()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, lspInfo.getNameAbbr()))
                    throw new BaseException("简称名不合法");
            //获取除自己外的相同名称信息，如果拥有不允许添加
            LspInfo nameExistLsp = this.getNameExistLsp(lspInfo);
            if (Objects.nonNull(nameExistLsp)) {
                throw new BaseException(LspEnum.LSP_NAME_EXIST.getCode(), "承运商名称或法人电话已被使用");
            }
            if (!Strings.isNullOrEmpty(lspInfo.getLegalRep()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, lspInfo.getLegalRep()))
                    throw new BaseException("法人姓名不合法");
            //将服务类型进行转换
            if (!CollectionUtils.isEmpty(lspInfo.getServiceTypeList())) {
                String sericeType = String.join(";", lspInfo.getServiceTypeList());
                lspInfo.setServiceType(sericeType);
            } else {
                lspInfo.setServiceType("");
            }
            if (!CollectionUtils.isEmpty(lspInfo.getBusinessSiteList())) {
                String businessSite = String.join(";", lspInfo.getBusinessSiteList());
                lspInfo.setBusinessSite(businessSite);
            } else {
                lspInfo.setBusinessSite("");
            }
            //新增或更新对应名称的信息并返回
            if (Objects.isNull(lspInfo.getId())) {
                JwtAccountVO jwtAccount = AccountUtil.getAccountInfoFromSecurityContext();
                //绑定验证信息
                lspInfo.setCode(String.valueOf(new Date().getTime()));
                lspInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
                lspInfo.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
                lspInfo.setCreateFrom(SourceEnum.LSPM.getText());
                lspInfo.setGmtCreate(new Date());
                lspInfo.setGmtUpdate(new Date());
                if (Objects.nonNull(jwtAccount)) {
                    lspInfo.setTenantId(new Long(jwtAccount.getTenantId()));
                    lspInfo.setCreator(jwtAccount.getAccountId());
                }
                this.insert(lspInfo);
                //绑定识别信息
                EnterpriseInfoVO enterpriseInfoVO = devopUtil.getEnterpriseInfoUrl(lspInfo.getName(), lspInfo.getCreditno());
                if (Objects.nonNull(enterpriseInfoVO)) {
                    if (Strings.isNullOrEmpty(enterpriseInfoVO.getRegcapital())) {
                        lspInfo.setRegistryCapital(new BigDecimal(0));
                    } else {
                        lspInfo.setRegistryCapital(new BigDecimal(enterpriseInfoVO.getRegcapital()));
                    }
                    lspInfo.setLegalRep(enterpriseInfoVO.getLegalperson());
                    lspInfo.setRegistrySite(enterpriseInfoVO.getRegaddress());
                    lspInfo.setCreditno(enterpriseInfoVO.getCreditno());
                    this.updateById(lspInfo);
                    //更新纳税人识别号
                    this.updateCreditnoByLspBasic(lspInfo);
                }
            } else {
                lspInfo.setGmtUpdate(new Date());
                lspInfo.setTenantId(null);
                if (AuthStatusEnum.CERTIFICATION.getCode().equals(lspInfo.getAuthStatus())) {
                    lspInfo.setName(null);
                } else {
                    //更新纳税人识别号
                    this.updateCreditnoByLspBasic(lspInfo);
                    if ("1".equals(lspInfo.getIsUpdate())) {
                        //同步刷新uaa
                        LspTaxpayerTenantVO tenantVO = new LspTaxpayerTenantVO();
                        tenantVO.setCorpName(lspInfo.getName());
                        tenantVO.setId(Integer.parseInt(lspInfo.getTenantId().toString()));
                        tenantVO.setTaxpayerId(lspInfo.getCreditno());
                        uaaUtil.tenantUpdateUrl(tenantVO, authorization);
                    }
                }
                this.updateById(lspInfo);
            }
            return lspInfo;
        } catch (BaseException e) {
            LOGGER.error("LspInfoServiceImpl.createLspInfo" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("LspInfoServiceImpl.createLspInfo" + e.getMessage());
            throw new BaseException("保存承运商信息失败!");
        }
    }

    @Override
    public LspBasicVO getLspBasic(Long lspId) {
        LspBasicVO lspBasicVO = new LspBasicVO();
        if (Objects.isNull(lspId)) throw new BaseException("请传入承运商信息");
        EntityWrapper<LspInfo> driverEntityWrapper = new EntityWrapper<>();
        driverEntityWrapper.eq("id", lspId);
        List<LspInfo> lspInfos = baseMapper.selectListNoTenant(driverEntityWrapper);
        LspInfo lspInfo = lspInfos.get(0);
        if (Objects.isNull(lspInfo)) throw new BaseException("未找到对应承运商信息");
        BeanUtils.copyProperties(lspInfo, lspBasicVO);
        //将服务类型进行转换
        if (!StringUtils.isEmpty(lspBasicVO.getServiceType())) {
            String[] sericeTypeList = lspBasicVO.getServiceType().split(";");
            lspBasicVO.setServiceTypeList(Lists.newArrayList(sericeTypeList));
        }
        if (!StringUtils.isEmpty(lspBasicVO.getBusinessSite())) {
            String[] businessSiteList = lspBasicVO.getBusinessSite().split(";");
            lspBasicVO.setBusinessSiteList(Lists.newArrayList(businessSiteList));
        }
        if (!StringUtils.isEmpty(lspInfo.getServiceType())) {
            List<TransportationTypeVO> allServiceType = mdmUtil.getAllTransportType();
            String serviceTypeName = lspInfo.getServiceType();
            for (TransportationTypeVO transportationTypeVO :
                    allServiceType) {
                serviceTypeName = serviceTypeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getValue());
            }
            lspBasicVO.setServiceTypeName(serviceTypeName);
        }
        String creditNo = this.getCreditnoByLspBasic(lspInfo);
        lspBasicVO.setCreditno(creditNo);
        return lspBasicVO;
    }

    @Override
    public LspInfo getLspByLspIdNoTenant(Long lspId) {
        EntityWrapper<LspInfo> ew = new EntityWrapper<>();
        ew.eq("id", lspId);
        List<LspInfo> lspInfos = baseMapper.selectListNoTenant(ew);
        return CollectionUtils.isEmpty(lspInfos) ? new LspInfo() : lspInfos.get(0);
    }

    /**
     * 获取公司信息
     *
     * @return
     */
    @Override
    public LspBasicVO getLspByLoginAccount() {
        JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
        if (Objects.isNull(jwtAccountVO)) throw new BaseException("获取登录信息异常");
        Long lspId = this.getLspIdByTenantId(Long.parseLong(jwtAccountVO.getTenantId()));
        if (Objects.isNull(lspId)) throw new BaseException("获取公司信息失败");
        return this.getLspBasic(lspId);
    }

    /**
     * 更新纳税人识别号
     *
     * @param lspInfo
     */
    private void updateCreditnoByLspBasic(LspBasicVO lspInfo) {
        LicenseVO licenseVO = new LicenseVO();
        licenseVO.setBelongedId(lspInfo.getId());
        licenseVO.setBelongedType("lsp");
        LicenseTypeVo licenseTypeBO = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.LSP_TAX_ID.getCode(), SubjectTypeEnum.LSP.getCode());
        if (Objects.isNull(licenseTypeBO)) {
            throw new BaseException("缺少证照类型");
        }
        LicenseDetailVO licenseDetailVO = new LicenseDetailVO();
        licenseDetailVO.setLicenseId(lspInfo.getCreditno());
        licenseDetailVO.setLicenseTypeId(licenseTypeBO.getId());
        licenseVO.addLicenseDetails(licenseDetailVO);
        licenseServier.updateLicense(licenseVO);
    }

    /**
     * 更新纳税人识别号
     *
     * @param lspInfo
     */
    private String getCreditnoByLspBasic(LspInfo lspInfo) {
        LicenseVO licenseVO = new LicenseVO();
        licenseVO.setBelongedId(lspInfo.getId());
        licenseVO.setBelongedType("lsp");
        LicenseTypeVo licenseTypeBO = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.LSP_TAX_ID.getCode(), SubjectTypeEnum.LSP.getCode());
        if (Objects.isNull(licenseTypeBO)) {
            throw new BaseException("缺少证照类型");
        }
        licenseVO.setLicenseTypeId(licenseTypeBO.getId());
        List<LicenseDetailVO> licenseDetailVOS = licenseServier.queryLicenseByBelongedId(licenseVO).getLicenseDetails();
        if (CollectionUtils.isEmpty(licenseDetailVOS)) return "";
        return licenseDetailVOS.get(0).getLicenseId();
    }

    /**
     * 获取名称内容重复的承运商信息
     *
     * @param lspInfo 包装承运商的实体，如果传入id则排除该id的承运商信息
     * @return 重复的承运商信息
     */
    private LspInfo getNameExistLsp(LspInfo lspInfo) {
        if (Objects.isNull(lspInfo)) return null;
        Wrapper<LspInfo> lspNameEntity = new EntityWrapper<>();
        if (!Objects.isNull(lspInfo.getId())) {
            lspNameEntity.ne("id", lspInfo.getId()).andNew();
        }
        lspNameEntity.eq("name", lspInfo.getName());
        lspNameEntity.or().eq("principal_mobile", lspInfo.getPrincipalMobile());
        if (!Strings.isNullOrEmpty(lspInfo.getNameAbbr()))
            lspNameEntity.or().eq("name_abbr", lspInfo.getNameAbbr());
        List<LspInfo> lspNameList = baseMapper.selectListNoTenant(lspNameEntity);
        if (!CollectionUtils.isEmpty(lspNameList)) {
            return lspNameList.get(0);
        }
        return null;
    }

    /**
     * 根据注册的租户信息，自动注册运输公司
     */
    @Transactional
    @Override
    @JmsListener(destination = "${mqName.tenant}", containerFactory = "jmsListenerContainerQueue")
    public void getLspIfon(String tenantInfoJson) {
        JSONObject json = JSONObject.parseObject(tenantInfoJson);
        LOGGER.info("tenantInfoJson params :{}", json);
        TenantInfoVO tenantInfoVO = json.toJavaObject(TenantInfoVO.class);
        String token = uaaUtil.getTenantToken("tech-" + tenantInfoVO.getTenantId());
        LOGGER.info("mqName.tenant params :{}", token);
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", token));
        HttpClientUtil.postJson(registerLspUrl, headNamePairs, tenantInfoJson, 1000);
    }

    @Override
    public Page<LspAccountVO> openAccountList(Page<LspAccountVO> page, String authorization) {
        Page<LspAccountVO> pageInfo = new Page<>();
        page.setAsc(false);
        Wrapper<LspAccountVO> lspAccountVOWrapper = new EntityWrapper<>();
        LicenseTypeVo licenseTypeVo = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.LSP_TAX_ID.getCode(), SubjectTypeEnum.LSP.getCode());
        lspAccountVOWrapper.eq("license_type_id", licenseTypeVo.getId());
        if (!Objects.isNull(page.getCondition())) {
            Object name = page.getCondition().get("name");
            if (!(Objects.isNull(name) || "".equals(name))) lspAccountVOWrapper.like("name", name.toString());
        }
        lspAccountVOWrapper.orderBy("i.gmt_create", false);
        List<LspAccountVO> lspAccountVOList = baseMapper.openAccountList(page, lspAccountVOWrapper);
        lspAccountVOList.forEach(LspAccountVO -> {
            List<NameValuePair> headNamePairs = Lists.newArrayList();
            List<NameValuePair> params = Lists.newArrayList();
            params.add(new BasicNameValuePair("corpName", LspAccountVO.getName()));
            headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
            String result = HttpClientUtil.get(uaaUrl + getTenantDredgeUrl, headNamePairs, params, socketTimeout);
            JSONObject jsonObject = JSONObject.parseObject(result);
            if (Integer.valueOf(jsonObject.get("code").toString()) == 0) {
                if (Boolean.valueOf(jsonObject.getJSONObject("data").get("dredge").toString())) {
                    LspAccountVO.setAccountStatus("已开通");
                } else {
                    LspAccountVO.setAccountStatus("未开通");
                }
                if (!StringUtils.isEmpty(jsonObject.getJSONObject("data").get("identifier")))
                    LspAccountVO.setLoginName(jsonObject.getJSONObject("data").get("identifier").toString());
                if (!StringUtils.isEmpty(jsonObject.getJSONObject("data").get("gmtCreate")))
                    LspAccountVO.setOpeningTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(jsonObject.getJSONObject("data").get("gmtCreate")));
            }
        });
        BeanUtils.copyProperties(page, pageInfo);
        pageInfo.setRecords(lspAccountVOList);
        return pageInfo;
    }

    /**
     * 根据id号，恢复指定承运商的删除状态
     *
     * @param ids
     * @return
     */
    @Override
    public List<String> updateDeleteStatus(List<Long> ids, String token) {
        try {
            List<String> msgs = new ArrayList<>();
            if (CollectionUtils.isEmpty(ids)) throw new BaseException("请选择恢复删除的承运商");
            for (Long id : ids) {
                String msg = "";
                EntityWrapper<LspInfo> lspInfoEntityWrapper = new EntityWrapper<>();
                lspInfoEntityWrapper.eq("id", id);
                List<LspInfo> infos = baseMapper.selectListNoTenant(lspInfoEntityWrapper);
                LspInfo lspInfo = infos.get(0);
                if (Objects.isNull(lspInfo)) {
                    msg = "承运商:" + lspInfo.getName() + ":承运商不存在";
                    msgs.add(msg);
                    continue;
                }
                if (Objects.nonNull(lspInfo.getTenantId())) {
                    try {
                        RestfulResponse rs = uaaUtil.unlockedTenant(lspInfo.getTenantId().toString(), token);
                        if (Objects.nonNull(rs)) {
                            if (rs.getCode() == -1) {
                                msg = "承运商:" + lspInfo.getName() + ":" + rs.getMessage();
                                msgs.add(msg);
                                continue;
                            }
                        }
                    } catch (Exception e) {
                        LOGGER.error("LspInfoServiceImpl.updateDeleteStatus ERROR:" + e.getMessage());
                        msg = "承运商:" + lspInfo.getName() + ":解锁账号失败";
                        msgs.add(msg);
                        continue;
                    }
                }
                baseMapper.updateDeleteStatus(lspInfoEntityWrapper);
            }
            return msgs;
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            LOGGER.error("LspInfoServiceImpl.updateDeleteStatus ERROR:" + e.getMessage());
            throw new BaseException("恢复失败");
        }
    }

    /**
     * 根据承运商Id批量获取承运商信息
     *
     * @param lspIds
     * @return
     */
    @Override
    public List<LspInfo> getLspName(List<Long> lspIds) {
        if (CollectionUtils.isEmpty(lspIds)) {
            throw new BaseException("未获取承运商");
        }
        List<LspInfo> lspInfos = this.selectBatchIds(lspIds);
        return lspInfos;
    }

    @Override
    public List<LspInfo> getAuthLsp() {
        Wrapper<LspInfo> lspInfoWrapper = new EntityWrapper<>();
        lspInfoWrapper.eq("auth_status", 1);
        return baseMapper.selectList(lspInfoWrapper);
    }

    /**
     * 根据租户id查询承运商信息
     *
     * @param tenantId
     */
    @Override
    public LspInfo queryLspInfoByTenantId(Long tenantId) {

        LspInfo cn = null;
        Wrapper<LspInfo> ew = new EntityWrapper<>();
        if (tenantId != null) {
            ew.eq("tenant_id", tenantId);
            List<LspInfo> lspInfo = baseMapper.selectListNoTenant(ew);
            if (!CollectionUtils.isEmpty(lspInfo)) {
                cn = lspInfo.get(0);
            }
        }
        return cn;
    }

    @Override
    public String lspToOtm(Long id) {
        if (Objects.isNull(id)) {
            throw new BaseException("id为空");
        }
        LspInfo lspInfo = this.selectById(id);
        if (Objects.isNull(lspInfo)) {
            throw new BaseException("未获取到承运商");
        }
        replaceServiceType(lspInfo);
        LspInfoDTO lspInfoDTO = new LspInfoDTO();
        BeanUtils.copyProperties(lspInfo, lspInfoDTO);
        lspInfoDTO.setIsActive(IntegrationEnum.ISACTIVE.getCode());
        String result = integrationUtil.exportLspToOTM(lspInfoDTO);
        return result;
    }

    @Override
    public List<LspInfo> getLspInfoAll(List<LspInfo> lspInfoList) {
        List<LspInfo> list = Lists.newArrayList();
        lspInfoList.forEach(lspInfo -> {
            HashMap<String, Object> map = Maps.newHashMap();
            map.put("name", lspInfo.getName());
            EntityWrapper<LspInfo> ew = this.queryLspInfoCheck(map);
            LspInfo lspInfoData = this.selectOne(ew);
            if (!ObjectUtils.isEmpty(lspInfoData)) {
                list.add(this.selectOne(ew));
            }
        });
        return list;
    }

    /**
     * 承运商查询条件
     *
     * @param condition 模糊查询字段
     */
    @Override
    public EntityWrapper<LspInfo> queryLspInfoCheck(Map<String, Object> condition) {
        EntityWrapper<LspInfo> ew = new EntityWrapper<>();
        if (!CollectionUtils.isEmpty(condition)) {
            //遍历条件
            for (Map.Entry<String, Object> entry : condition.entrySet()) {
                if (!Strings.isNullOrEmpty(entry.getKey())) {
                    //承运商全称
                    if ("name".equals(entry.getKey()) && !StringUtils.isEmpty(entry.getValue()))
                        ew.eq("name", String.valueOf(entry.getValue()));
                }
            }
        }
        return ew;
    }

    /**
     * 根据承运商名称批量模糊查询
     */
    @Override
    public Map<Long, Long> queryLspByName(List<ArFundDTO> arFundDTOS) {
        Map<Long, Long> map = Maps.newHashMap();
        if (!CollectionUtils.isEmpty(arFundDTOS)) {
            for (ArFundDTO arFundDTO : arFundDTOS) {
                if (!Objects.isNull(arFundDTO)) {
                    EntityWrapper<LspInfo> ew = new EntityWrapper<>();
                    ew.eq("name", arFundDTO.getLspName());
                    List<LspInfo> list = baseMapper.selectListNoTenant(ew);
                    if (!CollectionUtils.isEmpty(list))
                        map.put(arFundDTO.getId(), list.get(0).getId());
                }
            }
        }
        return map;
    }

    @Override
    public List<LspInfo> selectListNoTenant(Wrapper<LspInfo> ew) {
        return baseMapper.selectListNoTenant(ew);
    }

    @Override
    public UserInfoVO queryUserInfo(String phone) {
        if (StringUtils.isEmpty(phone)) {
            throw new BaseException("手机号为空");
        }

        UserInfoVO userInfoVO = new UserInfoVO();
        Wrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("mobile", phone)
                .or()
                .eq("email", phone);
        User user = userService.selectOne(userWrapper);
        if (user == null) {
            throw new BaseException("未查询到:" + phone + "的用户信息");
        }
        Wrapper<UserRole> userRoleWrapper = new EntityWrapper<>();
        userRoleWrapper.eq("user_id", user.getId());
        UserRole userRole = userRoleService.selectOne(userRoleWrapper);
        if (Objects.isNull(userRole)) {
            throw new BaseException("未授权,请联系管理人员授权!");
        }
        userInfoVO.setRoleId(userRole.getRoleId());
        userInfoVO.setName(user.getName());
        userInfoVO.setMobile(user.getMobile());
        if (Objects.nonNull(user.getLspId())) {
            userInfoVO.setLspId(user.getLspId());
            Wrapper<LspInfo> lspInfoWrapper = new EntityWrapper<>();
            lspInfoWrapper.eq("id", user.getLspId());
            LspInfo lspInfo = this.selectOne(lspInfoWrapper);
            if (lspInfo != null) {
                userInfoVO.setLspName(lspInfo.getName());
            }
        }
        Wrapper<FleetAdmin> fleetAdminEntityWrapper = new EntityWrapper<>();
        fleetAdminEntityWrapper.eq("mobile", user.getMobile());
        List<FleetAdmin> fleetAdmins = fleetAdminService.selectList(fleetAdminEntityWrapper);
        if (!CollectionUtils.isEmpty(fleetAdmins)) {
            StringBuilder sb = new StringBuilder();
            LinkedList<Long> fleetIds = Lists.newLinkedList();
            for (FleetAdmin fleetAdmin : fleetAdmins) {
                sb.append(fleetAdmin.getFleetId());
                if (fleetAdmins.size() >= 1) {
                    sb.append(",");
                }
                fleetIds.add(fleetAdmin.getFleetId());
            }
            userInfoVO.setFleetId(sb.substring(0, sb.length() - 1));

            //为运力采购系统登录返回车队信息
            EntityWrapper<Fleet> fleetEW = new EntityWrapper<>();
            fleetEW.in("id", fleetIds)
                    .orderBy("id", false);
            List<Fleet> fleets = fleetService.selectListNoTenant(fleetEW);
            Set<Long> lspSet = fleets.stream().map(Fleet::getLspId).collect(Collectors.toSet());
            EntityWrapper<LspInfo> lspEW = new EntityWrapper<>();
            lspEW.in("id", lspSet)
                    .orderBy("id", false);
            List<LspInfo> lspInfos = lspInfoService.selectListNoTenant(lspEW);
            userInfoVO.setFleets(fleets);
            userInfoVO.setLspInfos(lspInfos);
            userInfoVO.setRole("fleet");
        }
        return userInfoVO;
    }

    @Override
    public LspInfo selectByIdNoTenant(Long lspId) {
        return baseMapper.selectByIdNoTenant(lspId);
    }

    @Override
    public Map<String, Object> queryUserOpenId(String mobile) {
        if (StringUtils.isEmpty(mobile)) {
            throw new BaseException("手机号为空！");
        }
        Wrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("mobile", mobile).or().eq("email", mobile);
        User user = userService.selectOne(userWrapper);
        if (null == user) {
            throw new BaseException("未找到用户！");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("mobile", user.getMobile());
        map.put("openId", user.getOpenId());
        return map;
    }

    @Override
    public String addUserOpenId(User user) {
        if (null == user) {
            throw new BaseException("数据为空！");
        }
        if (StringUtils.isEmpty(user.getMobile())) {
            throw new BaseException("手机号为空！");
        }
        if (StringUtils.isEmpty(user.getOpenCode())) {
            throw new BaseException("OpenCode为空！");
        }
        String result;
        Wrapper<User> userWrapper = new EntityWrapper<>();
        userWrapper.eq("mobile", user.getMobile()).or().eq("email", user.getMobile());
        User userNew = userService.selectOne(userWrapper);

        if (null == userNew) {
            return "未查询到用户！";
        }

        if (StringUtils.isEmpty(userNew.getOpenId())) {
            // 对接微信获取openId
            String openId = WeiXinUtil.getOpenIdByCode(user.getOpenCode());

            userNew.setOpenId(openId);
            userService.updateById(userNew);
            return "添加成功！";
        }
        return "openId已存在！";
    }

    /**
     * 禁用承运商
     * @param condition
     * @param authorization
     * @return
     */
    @Override
    public String disableLsp(LspBasicVO condition, String authorization) {
        if (null == condition.getId()) {
            throw new BaseException("承运商id不能为空");
        }

        //判断该承运商是否有未安排(40)的报班任务
        List<DriverCheckin> driverCheckins=driverCheckinService.selectCheckinByLspId(condition.getId().toString());
        if (!CollectionUtils.isEmpty(driverCheckins)){
            throw new BaseException("还有未安排的报班任务");
        }

        //判断承运商下司机是否有未完成的任务
        List<NameValuePair> headNamePairs = Lists.newArrayList();
        headNamePairs.add(new BasicNameValuePair("Authorization", authorization));

         List<NameValuePair> pram = Lists.newArrayList();
         pram.add(new BasicNameValuePair("lspId", condition.getId().toString()));
         String lspWaybill = HttpClientUtil.get(lspWaybillUrl, headNamePairs, pram, socketTimeout);
         JSONObject lspWaybillJson = JSONObject.parseObject(lspWaybill);
         if ("false".equals(lspWaybillJson.get("data").toString())) {
                throw new BaseException("承运商下的司机还有未完成的运单");
         }

          // 更新承运商的业务状态
        if ("0".equals(condition.getStatus().toString())){
            throw new BaseException("承运商已禁用");
        }
        LspInfo lspInfo1 = new LspInfo();
        lspInfo1.setId(condition.getId());
        lspInfo1.setStatus(0);
        baseMapper.updateById(lspInfo1);
       // baseMapper.updateStatus(condition.getId().toString(),"0");


        LspInfo lspInfo = this.selectById(condition.getId().toString());
        if (Objects.isNull(lspInfo)) {
            throw new BaseException("未获取到承运商");
        }
        //replaceServiceType(lspInfo);
        LspInfoDTO lspInfoDTO = new LspInfoDTO();
        BeanUtils.copyProperties(lspInfo, lspInfoDTO);
        lspInfoDTO.setIsActive(IntegrationEnum.NOACTIVE.getCode());
        String result = integrationUtil.exportLspToOTM(lspInfoDTO);
        return result;
    }

    /**
     * 启用承运商
     * @param condition
     * @return
     */
    @Override
    public String enableLspInfo(LspBasicVO condition) {
        if (null == condition.getId()) {
            throw new BaseException("承运商id不能为空");
        }

        if (1 == condition.getStatus()) {
            throw new BaseException("承运商已经启用");
        }

        //更新承运商的业务状态
        LspInfo lspInfo1 = new LspInfo();
        lspInfo1.setId(condition.getId());
        lspInfo1.setStatus(1);
        baseMapper.updateById(lspInfo1);


        LspInfo lspInfo = this.selectById(condition.getId().toString());
        if (Objects.isNull(lspInfo)) {
            throw new BaseException("未获取到承运商");
        }
        LspInfoDTO lspInfoDTO = new LspInfoDTO();
        BeanUtils.copyProperties(lspInfo, lspInfoDTO);
        lspInfoDTO.setIsActive(IntegrationEnum.ISACTIVE.getCode());
        String result = integrationUtil.exportLspToOTM(lspInfoDTO);
        return result;
    }

    /**
     * 查询承运商
     * @param lspId
     * @return
     */
    @Override
    public LspInfo selectLspInfo(Long lspId) {
        return baseMapper.selectById(lspId);
    }

    @Override
    public LspInfo selectLspInfoByDriverId(Long id) {
        return baseMapper.selectLspInfoByDriverId(id);
    }


}
